//
//  XGHomeViewModel.swift
//  TodayNews
//
//  Created by monkey on 2020/3/25.
//  Copyright © 2020 itcast. All rights reserved.
//

import UIKit
import SwiftyJSON
import HandyJSON

class XGHomeViewModel
{    
    /// 新闻分类数组
    private(set) var newsCategories = [XGNewsCategoryModel]()
    /// 新闻数组
    private(set) var newsList = [XGNewsViewModel]()
}

extension XGHomeViewModel
{
    /// 获取首页新闻分类标题数据
    /// - Parameter completionHandle: 完成回调
    func fetchNewsCategories(completionHandle: @escaping(Bool) -> Void) -> Void
    {
        AlamofireTool.loadNewsCategoriesData { (responseObject, error) in
            if responseObject == nil || error != nil {
                XGPrint("加载新闻标题分类数据失败!")
                completionHandle(false)
                return
            }
            
            let jsonObject = JSON(responseObject!)
            guard let data = jsonObject["data"].dictionary,
                let dataArray = data["data"]?.array else {
                    // json解析错误
                    completionHandle(false)
                    return
            }
            
            self.newsCategories = dataArray.compactMap { return XGNewsCategoryModel.deserialize(from: $0.dictionaryObject) }
            completionHandle(true)
        }
    }
    
    /// 获取新闻列表
    /// - Parameters:
    ///   - category: 新闻分类
    ///   - isLoadMore: 是否是加载更多
    ///   - completionHandle: 完成回调
    func fetchNewsList(category: String, isLoadMore: Bool = false,completionHandle: @escaping(Bool) -> Void) -> Void
    {
        let min_behot_time = isLoadMore ? 0 : (newsList.first?.behotTime ?? 0)
        let max_behot_time = isLoadMore ? (newsList.last?.behotTime ?? 0) : 0
        AlamofireTool.loadNewsListData(category: category, min_behot_time: min_behot_time, max_behot_time: max_behot_time) { (responseObject, error) in
            if responseObject == nil || error != nil {
                XGPrint("加载新闻数据失败!")
                completionHandle(false)
                return
            }
            
            let jsonObject = JSON(responseObject!)
            let datas = jsonObject["data"].array
            DispatchQueue.global().async {
                let array = datas?.compactMap({ return XGNewsViewModel(newsModel: XGNewsModel.deserialize(from: $0["content"].string)!)})
                !isLoadMore ? self.newsList.removeAll() : ()
                self.newsList += array ?? []
                DispatchQueue.main.async {
                    completionHandle(true)
                }
            }
        }
    }
}
